package cn.edu.gdut.deepcode.controller;


import cn.edu.gdut.deepcode.domain.dto.CanvasOperationDTO;
import cn.edu.gdut.deepcode.domain.po.Result;
import cn.edu.gdut.deepcode.enums.OperationTypeEnum;
import cn.edu.gdut.deepcode.service.ICanvasOperationService;
import cn.edu.gdut.deepcode.utils.CommonUtils;
import cn.edu.gdut.deepcode.context.UserContext;
import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static cn.edu.gdut.deepcode.constant.AbnormalInfoConstant.CO_EI_2;
import static cn.edu.gdut.deepcode.constant.ReqRespConstant.AUTHORIZATION_HEADER_NAME;

/**
 * <p>
 * 画布操作表 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-04-11
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/canvas-operations")
public class CanvasOperationController {
    private final ICanvasOperationService canvasOperationService;

    @ApiOperation(value = "提交元素操作接口",notes = "响应体中的vo对象的elementId属性为null或者为元素id(新增时返回元素id)")
    @ApiImplicitParam(
            name = AUTHORIZATION_HEADER_NAME,
            value = "JWT 令牌",
            required = true,
            dataType = "string",
            paramType = "header"
    )
    @PostMapping
    public Result<Long> submitElement(
            @RequestBody CanvasOperationDTO canvasOperationDTO){
        if (BeanUtil.isEmpty(canvasOperationDTO)){
            CommonUtils.recordErrorInfoAndThrowException(
                    CO_EI_2,
                    List.of(UserContext.getUser(),canvasOperationDTO)
            );
        }
        if (canvasOperationDTO.getOperationType()!= OperationTypeEnum.INSERT){
            if (canvasOperationDTO.getElementId()==null||
                canvasOperationDTO.getVersion()==null
            ){
                // 类型不是新增且没(元素id或版本号)
                CommonUtils.recordErrorInfoAndThrowException(
                        CO_EI_2,
                        List.of(UserContext.getUser(),canvasOperationDTO)
                );
            }
        }
        return canvasOperationService.submitElement(canvasOperationDTO);
    }

}
